import React, { useEffect, useState } from 'react';
import { Form, Progress, notification } from 'antd';
import { connect } from 'dva';
import { axconst } from '@/shared/axconst';
import { AxUpdateForm } from '@/components/AxForm/AxUpdateForm';
import AxColumnEnum from '@/components/AxList/AxColumnEnum';
import AxTable from '@/components/AxList/AxTable';
import AxColumnAction from '@/components/AxList/AxColumnAction';
import { round } from 'lodash';

const RenderColor = (text: any, row: any, index?: any) => {
  if (row && row.isTryError === true) {
    const errorText = <span style={{ color: 'red' }}>{text}</span>;
    return errorText;
  } else return text;
};

const RenderColSpan = (text: any, row: any, colSpan: any) => {
  if (row && row.isTryError === true) {
    return {
      children: RenderColor(row.msgError, row),
      props: {
        colSpan: colSpan,
      },
    };
  } else return text;
};

/** 下载信息 */
const DownloadInfo: React.FC<any> = props => {
  const [data, setData] = useState({ list: [] });
  const {
    modelState: { downloadInfo },
    dispatch,
  } = props;
  const namespance = 'user';
  const columns = [
    {
      title: '导出类型',
      dataIndex: 'exportType',
      sorter: false,
      width: axconst.width.long,
      ellipsis: true,
      render: (text: any, row: any) =>
        RenderColor(<AxColumnEnum enumName="exportType" value={text} />, row),
    },
    {
      title: '导出时间',
      dataIndex: 'created',
      sorter: false,
      width: axconst.width.time,
      ellipsis: true,
      render: RenderColor,
    },
    {
      title: '处理进度',
      dataIndex: 'planCode',
      sorter: false,
      // width: axconst.width.longx,
      ellipsis: true,
      render: (text: any, row: any) => {
        let percent = 0;
        if (row.complete === true && row.dealCount === row.totalCount) {
          percent = 100;
        } else {
          percent = round((row.dealCount / row.totalCount) * 100);
        }
        return RenderColSpan(<Progress percent={percent} />, row, 2);
      },
    },
    {
      title: '下载文件',
      dataIndex: 'downUrl',
      sorter: false,
      // fixed: 'right',
      width: axconst.width.four,
      ellipsis: true,
      render: (val: any, row: any) => {
        let newVal: any = '';
        if (val)
          newVal = (
            <AxColumnAction
              buttons={[
                {
                  icon: 'download',
                  justIcon: true,
                  tip: '下载',
                  onClick: () => window.location.assign(val),
                },
              ]}
            />
          );
        else newVal = '暂无文件';
        return RenderColSpan(newVal, row, 0);
      },
    },
  ];

  useEffect(() => {
    dispatch({
      type: `${namespance}/fetchDownloadInfo`,
    });

    (window as any).ws.on('ReceiveMessage', (message: any) => {
      const res = JSON.parse(message);
      if (res && res.msgCode === '2000') {
        const error = res.msgError;
        if (error && error !== '') {
          notification.error({
            message: `请求错误`,
            description: error,
          });
          return;
        }
        setData((old, r = res) => {
          const d: any = r.data;
          const fd: any = old.list.find((i: any) => i.id === d.id);
          if (fd) {
            for (const key in d) {
              fd[key] = d[key];
            }
          } else {
            old.list.unshift(d as never);
          }
          return { list: old.list };
        });
      }
    });
  }, []);

  useEffect(() => {
    setData({ list: downloadInfo.list.map((i: any) => i) });
  }, [downloadInfo]);

  return (
    <AxUpdateForm
      {...props}
      title="下载信息"
      width="60%"
      footer={null}
      items={[
        <AxTable
          resizable
          checkboxModel={false}
          scroll={{ x: 'max-content', y: 240 }}
          style={{ minHeight: '240px' }}
          data={data}
          columns={columns}
        />,
      ]}
    />
  );
};

export default Form.create<any>()(
  connect((state: any) => ({
    modelState: state.user,
  }))(DownloadInfo),
);
